3
3
.
.
3
3
.
.
6
6
M
M
o
o
v
v
e
e
V
V
i
i
e
e
w
w
B
B
e
e
t
t
w
w
e
e
e
e
n
n
C
C
o
o
n
n
t
t
a
a
i
i
n
n
e
e
r
r
s
s
I
I
n
n
f
f
o
o
This tutorial shows how to move a View from one Container into the other.
Both Containers are populated with Views through Arrays.
To move View Between Containers we simply move associated Array Element between the Arrays.
Then when the Containers are redrawn Element associated with moved View will appear in the other Container.
E
E
x
x
a
a
m
m
p
p
l
l
e
e
In this example we have two VStack Containers: topContainer & bottomContainer .
Each will have their own topArray & bottomArray used to populate them with Text Views (one for each Array Element).
Then we use Tap Gesture to move one of the Text Views from the topContainer into bottomContainer.
We do this by removing Element associated with moved Text View from the topArray and adding it to bottomArray.
ContentView.swift
struct ContentView: View {
struct Element {
let myid : Int
let name : String
}
@State var leftArray : [Element] = [
Element( myid:1, name:"Left Element 1" ),
Element( myid:2, name:"Left Element 2" ),
Element( myid:3, name:"Left Element 3" )
]
@State var rightArray : [Element] = [
Element( myid:10, name:"Right Element 1" ),
Element( myid:20, name:"Right Element 2" ),
Element( myid:30, name:"Right Element 3" )
]
var body: some View {
HStack(spacing: 20) {
VStack(spacing: 20) {
ForEach(leftArray, id: \.myid) { element in
Text(element.name)
.onTapGesture{
print(element)
self.removeFromLeftArray(myid: element.myid)
}
}
}
VStack(spacing: 20) {
ForEach(rightArray, id: \.myid) { element in
Text(element.name)
.onTapGesture{
print(element)
self.removeFromRightArray(myid: element.myid)
}
}
}
}
}
func removeFromLeftArray(myid: Int) {
for (index, element) in leftArray.enumerated() {
if (element.myid == myid) {
leftArray.remove(at: index)
rightArray.append(element)
}
}
}
func removeFromRightArray(myid: Int) {
for (index, element) in rightArray.enumerated() {
if (element.myid == myid) {
rightArray.remove(at: index)
leftArray.append(element)
}
}
}
}
Initial Screen Click on Left Element 2 to move it into right Container